import axios from 'axios'

// 创建 axios 实例
const api = axios.create({
  baseURL: 'http://localhost:8000',
  timeout: 30000, // 30秒超时
  headers: {
    'Content-Type': 'multipart/form-data',
  },
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    console.log('API Request:', config.method?.toUpperCase(), config.url)
    return config
  },
  (error) => {
    console.error('Request error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    console.log('API Response:', response.status, response.config.url)
    return response
  },
  (error) => {
    console.error('Response error:', error.response?.status, error.message)
    return Promise.reject(error)
  }
)

// API 服务方法
export const apiService = {
  // 发送聊天消息
  async sendMessage(message, imageFile = null) {
    const formData = new FormData()
    formData.append('message', message)

    if (imageFile) {
      formData.append('image', imageFile)
    }

    try {
      const response = await api.post('/chat', formData)
      return response.data
    } catch (error) {
      console.error('Send message failed:', error)
      throw new Error(error.response?.data?.error || '发送消息失败')
    }
  },

  // 上传图片进行 OCR
  async uploadImageForOCR(imageFile) {
    const formData = new FormData()
    formData.append('file', imageFile)

    try {
      const response = await api.post('/ocr', formData)
      return response.data
    } catch (error) {
      console.error('OCR failed:', error)
      throw new Error(error.response?.data?.error || 'OCR识别失败')
    }
  },

  // 上传音频进行语音识别
  async uploadAudioForASR(audioBlob) {
    const formData = new FormData()
    formData.append('audio', audioBlob, 'recording.webm')

    try {
      const response = await api.post('/asr', formData)
      return response.data
    } catch (error) {
      console.error('ASR failed:', error)
      throw new Error(error.response?.data?.error || '语音识别失败')
    }
  },

  // 检查服务健康状态
  async checkHealth() {
    try {
      const response = await api.get('/health')
      return response.data
    } catch (error) {
      console.error('Health check failed:', error)
      throw new Error('服务健康检查失败')
    }
  },

  // 获取日志（如果需要）
  async getLogs(lines = 100) {
    try {
      const response = await api.get(`/logs?lines=${lines}`)
      return response.data
    } catch (error) {
      console.error('Get logs failed:', error)
      throw new Error('获取日志失败')
    }
  }
}

export default apiService
